package com.example.ec.controller;

import com.example.ec.model.User;
import com.example.ec.service.CommodityService;
import com.example.ec.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    private final UserService userService;
    private final CommodityService commodityService;

    public UserController(UserService userService, CommodityService commodityService) {
        this.userService = userService;
        this.commodityService = commodityService;
    }

    @PostMapping("create")
    private String create(User user) {
        if (userService.queryOne("queryUserByEmail", user) != null) {
            request.setAttribute("error", "Email已被注册，请换个Email注册");
            return "/signUp.jsp";
        }
        userService.create(user);
        return "redirect:/index.jsp";
    }



    @PostMapping("signIn")
    private String signIn(User user) {
        if ((user = userService.queryOne("queryUserByEmailPassword", user)) == null) {
            request.setAttribute("error", "用户名或密码有误，请重新输入！");
            return "/index.jsp";
        }
        System.out.println(user);
        session.setAttribute("user", user);
        if (user.getRole() == 0) {
            session.setAttribute("commodityList",commodityService.queryAll());
            return "redirect:/user/index.jsp";
        } else {
            session.setAttribute("commodityList",commodityService.queryAll());
            return "redirect:/admin/index.jsp";
        }
    }

    @GetMapping("loginOut")
    private String loginOut(){
        session.invalidate();
        return "redirect:/index.jsp";
    }






}
